//
//  ContentView.swift
//  MyCloset
//
//  Created by 牟好好 on 2024/10/20.
//

import SwiftUI

// 如果模型检测结果与服装部位没有交集，颜色没有交集等等，那就显示选项在屏幕上让用户必须勾选（服装部位必须勾选）
struct ContentView: View {
    @ObservedObject var coreVm = CoreDataViewModel.shared
    @StateObject var fileVm = FileManagerViewModel()
    let features1 = "上装，白色，牛仔"
    let features2 = "红色，上装，牛仔"
    let features3 = "下装，蓝色，格纹"
    let features4 = "下装，黄色，格纹"
    
    let recommendedCombinations: [[String]] = [
        ["白色", "黑色"],
        ["蓝色", "牛仔"],
        ["红色", "格纹"],
        ["米色", "棕色"],
    ]
    
    var body: some View {
        VStack {
            ForEach(coreVm.savedEntities) { entity in
                if let id = entity.id {
                    if let uiImage = fileVm.getImageFromFileManager(id: id) {
                        HStack {
                            Image(uiImage: uiImage)
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 200, height: 200)
                            
                            Text(entity.features ?? "")
                        }
                        .onTapGesture {
                            if let index = coreVm.savedEntities.firstIndex(where: { $0.id == id }) {
                                coreVm.deleteClothes(indexSet: IndexSet(integer: index))
                            }
                            fileVm.deleteImage(id: id)
                        }
                    }
                }
            }
        }
        .padding()
        .onAppear {
            let clothesComponent = ["上装", "下装", "帽子"]
            let currentFeature = features1
            let currentFeatureList = currentFeature.components(separatedBy: "，")
            // 获取当前服装部位
            let currentComponent = Set(clothesComponent).intersection(Set(currentFeatureList))
            
            var featureList = [features1, features2, features3, features4]
            // 将字符串转换为数组
            let featureArrayList = featureList.map({ $0.components(separatedBy: "，") })
            
            // 获取所有可搭配的特征
            let matchingFeatures = findMatchingCombinations(features: currentFeatureList, combinations: recommendedCombinations)
            
            var maxCount = 0
            // 最后修改为保存coreData中的index即可
            var results: [[String]] = []
            
            for item in featureArrayList {
                var matchCount: Int = 0
                // 上装与上装不能搭配
                if Set(item).isDisjoint(with: currentComponent) {
                    matchCount = findMatchingCount(features: item, combinations: matchingFeatures)
                    if matchCount > maxCount {
                        maxCount = matchCount
                        results = [item]
                    } else if matchCount == maxCount && maxCount != 0 {
                        results.append(item)
                    }
                }
            }
            
            print("与特征 \(features1) 搭配的特征是：\(matchingFeatures)")
            print(results)
        }
    }

    // 返回所有可搭配属性
    func findMatchingCombinations(features: [String], combinations: [[String]]) -> [String] {
        var matchingFeatures: Set<String> = []
        
        for combination in combinations {
            // isDisjoint 一个集合中是否没有与另一个集合相同的成员
            if !Set(combination).isDisjoint(with: Set(features)) {
                // 取交集
                matchingFeatures.formUnion(combination)
            }
        }
        
        return Array(matchingFeatures)
    }
    
    func findMatchingCount(features: [String], combinations: [String]) -> Int {
        // 交集数量
        let matchCount = Set(features).intersection(Set(combinations)).count
        print(matchCount)
        return matchCount
    }
}

#Preview {
    ContentView()
}
